
//获取父节点
export const getParentKey = (key, tree) => {
  let parentKey;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.itemNextList) {
      if (node.itemNextList.some(item => item.id === key)) {
        parentKey = node.id;
      } else if (getParentKey(key, node.itemNextList)) {
        parentKey = getParentKey(key, node.itemNextList);
      }
    }
  }
  return parentKey;
};

//扁平化树结构,遍历只获取所有节点的id
export function getNodeKey(nodes = [], arr = []) {
  for (let item of nodes) {
    arr.push(item.id);
    if (item.itemNextList && item.itemNextList.length)
      getNodeKey(item.itemNextList, arr);
  }
  return arr;
}

//正序获取当前id的所有父节点 包含当前id本身节点
export function getParent(data2, nodeId2) {
  var arrRes = [];
  if (data2.length == 0) {
    if (nodeId2) {
      arrRes.unshift(data2);
    }
    return arrRes;
  }
  let rev = (data, nodeId) => {
    for (var i = 0, length = data.length; i < length; i++) {
      let node = data[i];
      if (node.id == nodeId) {
        arrRes.unshift(node);
        rev(data2, node.parentId);
        break;
      }
      if (node.itemNextList) {
        rev(node.itemNextList, nodeId);
      }
    }
    return arrRes;
  };
  arrRes = rev(data2, nodeId2);
  return arrRes;
}

/**
 * 树形结构数据， 已知某一子节点 ，依次向上获取所有父节点
 * @param {*树形结构} tree
 * @param {*已知节点属性(代码中判断id相等)} nodeId
 * @returns
 */
export function treeFindPath(tree, nodeId) {
  var path = [];
  if (!tree) return [];
  var forFn = function(tree, nodeId) {
    for (var i = 0; i < tree.length; i++) {
      // 存放最后返回的内容,返回text集合
      var data = tree[i];
      path.push(data);
      if (data.id === nodeId) return path;
      if (data.itemNextList) {
        const itemNextList = forFn(data.itemNextList, nodeId);
        if (itemNextList) return itemNextList;
      }
      path.pop();
    }
  };
  forFn(tree, nodeId);
  return path;
}

//给指定节点添加属性, 主要是添加disabled属性
export const insertProp = (json, nodeIds, bol) => {
  var arr = json.map(item => {
    if (nodeIds.includes(item.id)) {
      item.disabled = bol;
    }
    if (item.itemNextList) {
      insertProp(item.itemNextList, nodeIds, bol);
    }
    return item;
  });
  return arr;
};

//格式化树结构,为节点添加parentId
export const formatTreeList = list => {
  list.itemNextList &&
    list.itemNextList.map(item => {
      item.parentId = list.id;
      item.scopedSlots = { title: "title" };
      formatTreeList(item);
      return item;
    });
};

//获取子节点的父级id
export const getParentIds = (keys,tree) => {
    const obj = {}
    //便利tree的itemList
    const findIds = (itemNextList) => {
      if(!itemNextList) {
        return
      }
      itemNextList.forEach(item => {
        if(keys.includes(item.id)) {
          if(!obj[item.id]) {
            obj[item.id] = []
          }
          obj[item.id].push(item.parentId)
        }
        findIds(item.itemNextList)
      })
    }
    findIds(tree)
    return obj
}
